<template>
  <div class="app-container">
    <detail-table :columns="columns" :detail="detail" :label-width="100" />
    <my-table
      class="child-my-table"
      :label-width="120"
      :columns="tableColumns"
      :data-source="sendList"
      :btn-options="btnOptions"
      :pagination="pagination"
      title="送教提报列表"
      @page-change="handlePageChange"
    >
      <div slot="table-btn">
        <el-button v-if="detail.status !== 2" v-permission="[settings.teacherPerm]" type="primary" @click="addRecordFn">新增送教提报</el-button>
      </div>
    </my-table>
    <send-record-dialog
      :visible="visible"
      :is-verify="type === 'verify'"
      :detail="detailObj"
      @transferData="handleDialogEvent"
    />
    <el-dialog
      title="新增送教提报"
      :visible.sync="addVisible"
      width="50%"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px">
        <el-form-item label="提报类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择提报类型" :disabled="dialogType === 'edit'" @change="changeType">
            <el-option v-for="item in recordTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 5" label="期末评价" prop="endTermAssess">
          <my-upload v-model="ruleForm.teachAssess" list-type="text" img-type="pdf,PDF" />
          <div v-if="!ruleForm.teachAssess || ruleForm.teachAssess.length === 0" style="color: #bbb;">请上传pdf格式的文件</div>
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 1" label="送教教学计划" prop="teachPlan">
          <my-upload v-model="ruleForm.teachPlan" list-type="text" img-type="pdf,PDF" />
          <div v-if="!ruleForm.teachPlan || ruleForm.teachPlan.length === 0" style="color: #bbb;">请上传pdf格式的文件</div>
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 4" label="送教总结" prop="teachSummary">
          <my-upload v-model="ruleForm.teachSummary" list-type="text" img-type="pdf,PDF" />
          <div v-if="!ruleForm.teachSummary || ruleForm.teachSummary.length === 0" style="color: #bbb;">请上传pdf格式的文件</div>
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 3" label="美篇链接" prop="publicityArticle">
          <el-input v-model="ruleForm.publicityArticle" />
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 2" label="送教时间" prop="outTime">
          <el-date-picker
            v-model="ruleForm.outTime"
            type="date"
            placeholder="请选择送教时间"
          />
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 2" label="送教地点" prop="outAddress">
          <el-input v-model="ruleForm.outAddress" />
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 2" label="送教教案（课时1）" prop="teachBookA">
          <my-upload v-model="ruleForm.teachBookA" :limit="5" />
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 2" label="送教现场（课时1）" prop="workSceneA">
          <my-upload v-model="ruleForm.workSceneA" :limit="5" />
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 2" label="送教教案（课时2）" prop="teachBookB">
          <my-upload v-model="ruleForm.teachBookB" :limit="5" />
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 2" label="送教现场（课时2）" prop="workSceneB">
          <my-upload v-model="ruleForm.workSceneB" :limit="5" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSendRecord">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import { getTaskDetail, addRecord, getSendRecordList, recordDetail, delRecord, verifyRecord } from '@/api/task'
import DetailTable from '@/components/detail-table/index'
import MyTable from '@/components/my-table/index'
import MyUpload from '@/components/my-upload/index'
import settings from '@/settings'
import SendRecordDialog from '../../components/send-record-dialog/index'
import { sendTaskDetailColumns, sendRecordCol } from '../../columns'
import { recordTypeOptions } from '../../attr'

export default {
  components: { DetailTable, MyTable, SendRecordDialog, MyUpload },
  data() {
    const that = this
    return {
      settings,
      recordTypeOptions,
      dialogType: 'add',
      columns: sendTaskDetailColumns,
      tableColumns: sendRecordCol,
      detail: {},
      sendList: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      btnOptions: [
        {
          name: '查看详情',
          handler: function(row) {
            that.openRecordDialog(row, 'watch')
          }
        },
        {
          name: '编辑',
          permission: [settings.teacherPerm],
          v_if: row => row.status === 0,
          handler: function(row) {
            that.editRecordFn(row)
          }
        },
        {
          name: '删除',
          permission: [settings.teacherPerm],
          v_if: row => row.status === 0,
          handler: function(row) {
            that.deleteRecord(row)
          }
        },
        {
          name: '审核',
          permission: [settings.managePerm],
          v_if: row => row.status === 0,
          handler: function(row) {
            that.openRecordDialog(row, 'verify')
          }
        }
      ],
      // dialog配置
      visible: false,
      type: 'watch', // watch 查看  verify 审核
      detailObj: {},
      // 新增记录弹窗配置
      addVisible: false,
      ruleForm: {},
      rules: {
        type: [
          { required: true, message: '请选择提报类型', trigger: 'change' }
        ],
        endTermAssess: [
          { required: true, message: '请上传期末评价', trigger: 'change' }
        ],
        teachPlan: [
          { required: true, message: '请上传教学计划', trigger: 'change' }
        ],
        teachSummary: [
          { required: true, message: '请上传送教总结', trigger: 'change' }
        ],
        publicityArticle: [
          { required: true, message: '请填写美篇链接', trigger: 'blur' }
        ],
        outTime: [
          { required: true, message: '请选择送教时间', trigger: 'change' }
        ],
        outAddress: [
          { required: true, message: '请填写送教地点', trigger: 'blur' }
        ],
        teachBookA: [
          { required: true, message: '请上传课时1的送教教案', trigger: 'change' }
        ],
        teachBookB: [
          { required: true, message: '请上传课时2的送教教案', trigger: 'change' }
        ],
        workSceneA: [
          { required: true, message: '请上传课时1的送教现场', trigger: 'change' }
        ],
        workSceneB: [
          { required: true, message: '请上传课时1的送教现场', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getDetail()
    this.handlePageChange()
  },
  methods: {
    changeType(type) {
      this.ruleForm = JSON.parse(JSON.stringify({
        type
      }))
    },
    async getDetail() {
      try {
        const res = await getTaskDetail({ id: this.$route.params.id })
        if (res) {
          this.detail = res
        }
      } catch (err) {
        console.log('接口出错')
      }
    },
    async handleDialogEvent(type) {
      const that = this
      if (type === 'close') {
        this.visible = false
      } else if (type === 'verify') {
        try {
          const res = await verifyRecord({
            id: this.detailObj.outworkRecordId
          })
          if (res) {
            that.$message({
              message: `审核提报记录成功！`,
              type: 'success'
            })
            that.handlePageChange(that.pagination.current)
            that.visible = false
          }
        } catch (err) {
          console.log('接口出错')
        }
      }
    },
    openRecordDialog(row, type) {
      const that = this
      this.getRecordDetail(row.outworkRecordId, function(data) {
        that.type = type
        that.visible = true
        that.detailObj = data
      })
    },
    addRecordFn() {
      this.addVisible = true
      this.ruleForm = {
        type: ''
      }
      this.dialogType = 'add'
    },
    editRecordFn(row) {
      const that = this
      this.getRecordDetail(row.outworkRecordId, function(data) {
        that.addVisible = true
        that.dialogType = 'edit'
        that.ruleForm = data
        if (data.teachAssess) {
          that.ruleForm.teachAssess = data.teachAssess.map(v => ({
            url: v,
            name: '送教评估表'
          }))
        }
        if (data.teachPlan) {
          that.ruleForm.teachPlan = data.teachPlan.map(v => ({
            url: v,
            name: '送教计划文档'
          }))
        }
        if (data.teachSummary) {
          that.ruleForm.teachSummary = data.teachSummary.map(v => ({
            url: v,
            name: '送教总结文档'
          }))
        }
        if (data.teachBookA) {
          that.ruleForm.teachBookA = data.teachBookA.map(v => ({
            url: v
          }))
        }
        if (data.teachBookB) {
          that.ruleForm.teachBookB = data.teachBookB.map(v => ({
            url: v
          }))
        }
        if (data.workSceneA) {
          that.ruleForm.workSceneA = data.workSceneA.map(v => ({
            url: v
          }))
        }
        if (data.workSceneB) {
          that.ruleForm.workSceneB = data.workSceneB.map(v => ({
            url: v
          }))
        }
      })
    },
    async deleteRecord(row) {
      const that = this
      this.$confirm('确定要删除该提报记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        try {
          const res = await delRecord({ id: row.outworkRecordId })
          if (res) {
            that.$message({
              message: `删除提报记录成功！`,
              type: 'success'
            })
            that.handlePageChange(that.pagination.current)
          }
        } catch (err) {
          console.log('接口出错')
        }
      })
    },
    async getRecordDetail(id, cb) {
      try {
        const res = await recordDetail({ id })
        if (res) {
          cb(res)
        }
      } catch (err) {
        console.log('接口出错')
      }
    },
    addSendRecord() {
      const that = this
      this.$refs['ruleForm'].validate(async(valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(that.ruleForm))
          params.outworkId = Number(that.$route.params.id)
          if (params.teachAssess) {
            params.teachAssess = params.teachAssess.map(v => v.url)
          }
          if (params.teachBookA) {
            params.teachBookA = params.teachBookA.map(v => v.url)
          }
          if (params.teachBookB) {
            params.teachBookB = params.teachBookB.map(v => v.url)
          }
          if (params.workSceneA) {
            params.workSceneA = params.workSceneA.map(v => v.url)
          }
          if (params.workSceneB) {
            params.workSceneB = params.workSceneB.map(v => v.url)
          }
          if (params.teachPlan) {
            params.teachPlan = params.teachPlan.map(v => v.url)
          }
          if (params.teachSummary) {
            params.teachSummary = params.teachSummary.map(v => v.url)
          }
          if (params.outTime) {
            params.outTime = moment(params.outTime).format('YYYY-MM-DD')
          }
          try {
            const res = await addRecord(params)
            if (res) {
              that.$message({
                message: `${this.dialogType === 'edit' ? '编辑' : '新增'}提报成功！`,
                type: 'success'
              })
              // 刷新提报列表
              that.handlePageChange(that.pagination.current)
              that.addVisible = false
            }
          } catch (err) {
            this.$message.error(err.desc)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async handlePageChange(current, size) {
      if (current) {
        this.pagination.current = current
      }
      if (size) {
        this.pagination.pageSize = size
      }
      this.loading = true
      try {
        const res = await getSendRecordList({
          outworkId: this.$route.params.id,
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
        if (res && res.list) {
          this.sendList = res.list
          this.pagination = {
            current: res.pageNum,
            pageSize: res.pageSize,
            total: res.totalElements
          }
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    }
  }
}
</script>
<style scoped lang="less">
  .app-container {
    background: #fff;
  }
</style>
